package com.hjb.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.hjb.entity.Database;
import com.hjb.service.IDatabaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HuJiaBing
 * @date 2025/7/4 13:52
 * @description
 */
@Slf4j
@Component
public class DynamicDatasourceHelper {

    @Resource
    private IDatabaseService databaseService;

    public Connection getConnection(Database database) {
        DataSource dataSource = (DruidDataSource) DynamicDatasource.getDataSourceMap().get(database.getId());
        if (dataSource == null) {
            dataSource = DynamicDatasource.init(database, false);
        }
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            log.error("获取数据库连接失败：{}", e.getMessage());
        }
        return connection;
    }
    public boolean testConnection(Database database) {
        DataSource dataSource = (DruidDataSource) DynamicDatasource.getDataSourceMap().get(database.getId());
        if (dataSource == null) {
            dataSource = DynamicDatasource.init(database, false);
        }
        Connection connection = null;
        try {
             connection = dataSource.getConnection();
            return connection != null;
        } catch (SQLException e) {
            log.error("测试数据库连接失败：{}", e.getMessage());

        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error("关闭数据库连接失败", e);

                }
            }
        }
        return false;
    }

    public Map<String, String> getTables(String id) {
        Database database = databaseService.getById(id);
        Connection connection = this.getConnection(database);
        if (connection == null) {
            log.error("获取连接失败");
            throw new RuntimeException("获取连接失败");
        }
        Map<String, String> tableMap = new LinkedHashMap<>();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables(database.getDbName(), null, "%", new String[]{"TABLE"});
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                String remarks = tables.getString("REMARKS");
                tableMap.put(tableName, remarks);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tableMap;

    }
}
